<?php


namespace App\Service;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;

class BatchNotify
{


    /**
     * 此函数将序列化subscriptionTopic-> sendNotification-> unsubscribeTopic
     * @param $deviceTokens
     * @param $data
     * @throws GuzzleException
     */
    public function sendBatchNotification($deviceTokens, $data = [])
    {
//        self::subscribeTopic($deviceTokens, $data['topicName']);
        self::sendNotification($data, $deviceTokens);
//        self::sendNotification($data, $data['topicName']);  // 备用
//        self::unsubscribeTopic($deviceTokens, $data['topicName']);
    }


    /**
     * 基于注册的主题名称和设备令牌，此功能根据通过功能发送的主题发送通知subscribeTopic，即属性的含义
     * to：了解主题推送通知 +通知：通知的标题和内容 apns（用于IOS）：预定义的选项，例如图像。 +数据：添加自定义属性。
     * @param $data
     * @param $topicName
     * @throws GuzzleException
     */
    public function sendNotification($data, $deviceTokens = null)
    {
        $url = 'https://fcm.googleapis.com/fcm/send';
        // 选用参数例子 可参考 new Push();
        $data = [
//            'to' => '/topics/' . $topicName,   // 单个发送的时候可以用
            'registration_ids' => $deviceTokens,
            'notification' => [
                'body' => $data['body'] ?? 'notification-Some-thing-body',
                'title' => $data['title'] ?? 'notification-Something-title',
                'image' => $data['image'] ?? null,
            ],
            'data' => [
                'title' => $data['title'] ?? 'Something-title',
                'body'  => $data['body'] ?? 'Some-thing-body',
                'sound' => $data['sound'] ?? 'default',
//                'click_action' => $data['sound'] ?? '',  // 是否可点击
//                'icon' => $data['icon'] ?? '',  // icon
                'image' => $data['image'] ?? null,
                'apns' => [
                    'payload' => [
                        'aps' => [
                            'mutable-content' => 1,
                            'category' => 'NEW_MESSAGE_CATEGORY'
                        ],
                    ],
                    'fcm_options' => [
                        'image' => $data['image'] ?? null,
                    ],
                    'headers' => ['apns-priority'=>'5']
                ],
                'android'=> [
                    'ttl' => date( 'Y-m-d H:i:s' ),
                    "notification" => [
                        'click_action' => 'OPEN_ACTIVITY_1'
                    ]
                ],
                "webpush" => [
                    'headers' => ['Urgency'=> 'high']
                ]
            ],
        ];

        $this->execute($url, $data);
    }



    /**
     * 实现此功能以订阅Firebase上的主题，并与多个设备令牌一起使用
     * @param $deviceToken
     * @param $topicName
     * @throws GuzzleException
     */
    public function subscribeTopic($deviceTokens, $topicName = null)
    {
        $url = 'https://iid.googleapis.com/iid/v1:batchAdd';
        $data = [
            'to' => '/topics/' . $topicName,
            'registration_tokens' => $deviceTokens,
        ];

        $this->execute($url, $data);
    }



    /**
     * 此功能用于取消订阅Firebase上的主题（取消主题），并且可以使用许多设备令牌
     * @param $deviceToken
     * @param $topicName
     * @throws GuzzleException
     */
    public function unsubscribeTopic($deviceTokens, $topicName = null)
    {
        $url = 'https://iid.googleapis.com/iid/v1:batchRemove';
        $data = [
            'to' => '/topics/' . $topicName,
            'registration_tokens' => $deviceTokens,
        ];

        $this->execute($url, $data);
    }



    /**
     * @param $url
     * @param array $dataPost
     * @param string $method
     * @return bool
     * @throws GuzzleException
     */
    private function execute($url, $dataPost = [], $method = 'POST')
    {
        $result = false;
        try {
            $client = new Client();
            $result = $client->request($method, $url, [
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Authorization' => 'key=' . env('FCM_SERVER_KEY'),
                ],
                'json' => $dataPost,
                'timeout' => 300,
            ]);
            $content = json_decode( $result->getBody(), true );
            print_r($content);
            $resp = $result->getStatusCode() == Response::HTTP_OK;
            // 可以记录错误的数据
            Log::debug('result-execute',['executeData'=>$result,'result'=>$resp,'dataPost'=>$dataPost]);

        } catch (\Exception $e) {
            Log::debug($e->getMessage());
        }

        return $result;
    }


}